package com.ljx.javaredis.service.impl;

import com.ljx.javaredis.dao.DeptDao;
import com.ljx.javaredis.entiey.Dept;
import com.ljx.javaredis.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * redis缓存模式
 * @author LJX
 * @Description: TODO
 * @Date: 2022/12/7 15:58
 * @Version 1.0
 */
@Service
public class DeptServiceImpl2 implements DeptService {
	@Resource
	private DeptDao deptDao;

	@Autowired
	private RedisTemplate<String,Object> redisTemplate;

	@Override
	/**
	 * 	查询，如果命中则不执行该注解的方法体，如果没有命中则执行方法体，并把返回的结果存入缓存中
	 * 	cacheNames,缓存的名称
	 * 	key:唯一区分 #deptno读取方法的参数名的值
 	 */
	@Cacheable(cacheNames = "redis::dept2",key = "#deptno")
	public Dept findById(int deptno) {
		Dept dept = deptDao.selectById(deptno);
		return dept;
	}

	@Override
	// 删除先执行方法体，再执行删除缓存（即为现删除数据库后删除缓存）
	@CacheEvict(cacheNames = "redis::dept2",key = "#deptno")
	public int deleteById(int deptno) {
		int i = deptDao.deleteById(deptno);
		return 8888;
	}

	@Override
	public int insetToDept(Dept dept) {
		// 向数据表中添加数据
		return deptDao.insert(dept);
	}

	@Override
	// 修改，先执行方法体，再把方法体返回的结果放入缓存
	@CachePut(cacheNames = "redis::dept2",key = "#dept.deptno")
	public int updateById(Dept dept) {
		int i = deptDao.updateById(dept);
		return i;
	}
}
